import * as THREE from 'three'

let camera, scene, renderer
//鼠标响应
let mouseX = 0, mouseY = 0
let material

initCamera()
initScene()
initAxesHelper()
initMeshes()
initRenderer()

animate()

window.addEventListener('resize',function (params) {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(this.window.innerWidth,this.window.innerHeight)
})

//消息响应
document.body.touchAction = 'none'
document.body.addEventListener("pointermove", function (event) {
    if(event.isPrimary === false) return
    mouseX = event.clientX - window.innerWidth / 2;
    mouseY = event.clientY - window.innerHeight / 2;
})

function initRenderer(params) {
    renderer = new THREE.WebGLRenderer({ antialias: true })
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)
    document.body.appendChild(renderer.domElement)
}

function initCamera(params) {
    camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 2, 2000)
    camera.position.z = 1000
}

function initScene(params) {
    scene = new THREE.Scene()
    scene.fog = new THREE.FogExp2(0x000000,0.001)
}

function initAxesHelper(params) {
    scene.add(new THREE.AxesHelper(100))
}

function initMeshes() {

    //geometry
    const geometry = new THREE.BufferGeometry()
    const vertices = []
    for (let i = 0; i < 10000; i++){
        const x = 2000 * Math.random() - 1000
        const y = 2000 * Math.random() - 1000
        const z = 2000 * Math.random() - 1000
        vertices.push(x,y,z)
    }
    geometry.setAttribute(
        'position',
        new THREE.Float32BufferAttribute(vertices, 3)
    );
    console.log(geometry);

    //material

    //给粒子添加材质
    const texture = new THREE.TextureLoader().load('textures/sprites/snowflake7_alpha.png')
     material = new THREE.PointsMaterial({
        alphaTest: 0.5,
        transparent:true,
         size: 20,
        //稀薄属性
         sizeAttenuation:true,
        map:texture
    })
    
    //Points
    const particles = new THREE.Points(geometry, material)
    scene.add(particles)

}

function animate(params) {
    requestAnimationFrame(animate)
    render()
}

function render(params) {

    const time = Date.now() * 0.00005
    camera.position.x += (mouseX - camera.position.x) * 0.05
    camera.position.y += (mouseY - camera.position.y) * 0.05
    camera.lookAt(scene.position)
    
    const h = (360 * (1.0 + time) % 360) / 260;
    material.color.setHSL(h,0.5,0.5)

    renderer.render(scene,camera)
}
